package com.changgou.order.consumer;

import com.alibaba.fastjson.JSON;
import com.changgou.order.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author tang.qingbo
 * @Date 2020/9/7 23:54
 * @Version 1.0
 */
@Component
//从配置文件中获取需要监听的队列名
@RabbitListener(queues = "${mq.pay.queue.order}")
public class OrderPayMessageListener {
    @Autowired
    private OrderService orderService;

    /**
     * 监听队列
     * @param message 监听到的队列信息
     */
    @RabbitHandler
    public void consumerMessage(String message) {
        //将消息转为map类型
        Map<String,String> dataMap = JSON.parseObject(message, Map.class);
        //获取返回状态码 return_code
        String returnCode = dataMap.get("return_code");
        //获取业务结果 result_code
        String resultCode = dataMap.get("result_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            //获取商户订单号 out_trade_no 就是我们的orderId
            String outTradeNo = dataMap.get("out_trade_no");
            if ("SUCCESS".equalsIgnoreCase(resultCode)) {
                if (outTradeNo != null) {
                    //获取微信交易流水号 transaction_id
                    String transactionId = dataMap.get("transaction_id");
                    //代表支付成功 == 修改订单状态  写入数据库  删除redis缓存中的数据
                    orderService.updateStatus(outTradeNo, transactionId);
                }
            } else {
                //支付失败 修改订单状态为支付失败 redis中删除
                orderService.deleteOrder(outTradeNo);
            }
        }
    }
}
